package src;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class PaymentInfoPanel extends JDialog {
    private Connection connection;
    private JTable paymentTable;
    private JTextField idField, billIdField, paymentDateField, amountField;
    private JComboBox<String> paymentMethodCombo, salesmanCombo;
    private JButton addButton, updateButton, deleteButton, searchButton;
    private JPanel inputPanel;

    public PaymentInfoPanel(Connection connection) {
        super((JFrame) null, "客户费用及收费管理", true);
        this.connection = connection;
        setSize(1000, 700);
        setLocationRelativeTo(null);
        getContentPane().setBackground(StyleConstants.BACKGROUND_COLOR);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(StyleConstants.THEME_COLOR);
        JLabel titleLabel = new JLabel("客户费用及收费管理", JLabel.CENTER);
        titleLabel.setFont(StyleConstants.TITLE_FONT);
        titleLabel.setForeground(Color.WHITE);
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"ID", "账单", "支付日期", "金额", "支付方式", "业务员"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        paymentTable = new JTable(model);
        paymentTable.setFont(StyleConstants.TABLE_FONT);
        paymentTable.getTableHeader().setFont(StyleConstants.TABLE_FONT);
        paymentTable.setRowHeight(25);
        paymentTable.setGridColor(StyleConstants.THEME_COLOR);
        JScrollPane scrollPane = new JScrollPane(paymentTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建输入面板
        inputPanel = new JPanel(new GridLayout(7, 2, 10, 10));
        inputPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        addInputField(inputPanel, "ID:", idField = new JTextField());
        addInputField(inputPanel, "账单:", billIdField = new JTextField());
        addInputField(inputPanel, "支付日期:", paymentDateField = new JTextField());
        addInputField(inputPanel, "金额:", amountField = new JTextField());
        
        // 添加支付方式下拉框
        paymentMethodCombo = new JComboBox<>(new String[]{"微信", "支付宝", "银行卡", "现金"});
        addComboBox("支付方式:", paymentMethodCombo);
        
        // 添加业务员下拉框
        salesmanCombo = new JComboBox<>();
        salesmanCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT salesman_id, name FROM salesman");
            while (rs.next()) {
                String salesmanId = rs.getString("salesman_id");
                String salesmanName = rs.getString("name");
                salesmanCombo.addItem(salesmanName + " (" + salesmanId + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载业务员信息失败: " + e.getMessage());
        }
        addComboBox("业务员:", salesmanCombo);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(StyleConstants.BACKGROUND_COLOR);

        addButton = createStyledButton("添加");
        updateButton = createStyledButton("更新");
        deleteButton = createStyledButton("删除");
        searchButton = createStyledButton("查找");

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(searchButton);

        // 将输入面板和按钮面板添加到主面板
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        bottomPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        bottomPanel.add(inputPanel, BorderLayout.CENTER);
        bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
        refreshTable();

        // 添加表格选择监听器
        paymentTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = paymentTable.getSelectedRow();
                if (selectedRow != -1) {
                    idField.setText(paymentTable.getValueAt(selectedRow, 0).toString());
                    billIdField.setText(paymentTable.getValueAt(selectedRow, 1).toString());
                    paymentDateField.setText(paymentTable.getValueAt(selectedRow, 2).toString());
                    amountField.setText(paymentTable.getValueAt(selectedRow, 3).toString());
                    paymentMethodCombo.setSelectedItem(paymentTable.getValueAt(selectedRow, 4).toString());
                    
                    // 设置业务员下拉框选中项
                    String selectedSalesman = paymentTable.getValueAt(selectedRow, 5).toString();
                    for (int i = 0; i < salesmanCombo.getItemCount(); i++) {
                        String item = salesmanCombo.getItemAt(i);
                        if (item != null && item.equals(selectedSalesman)) {
                            salesmanCombo.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            }
        });

        // 添加按钮事件监听器
        addButton.addActionListener(e -> {
            PaymentAddDialog dialog = new PaymentAddDialog(this, connection);
            dialog.setVisible(true);
            refreshTable();
        });
        updateButton.addActionListener(e -> updatePayment());
        deleteButton.addActionListener(e -> deletePayment());
        searchButton.addActionListener(e -> searchPayment());
    }

    private void addInputField(JPanel panel, String labelText, JTextField textField) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        panel.add(label);
        textField.setFont(StyleConstants.LABEL_FONT);
        panel.add(textField);
    }

    private void addComboBox(String labelText, JComboBox<String> comboBox) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(label);
        comboBox.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(comboBox);
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(StyleConstants.BUTTON_FONT);
        button.setBackground(StyleConstants.BUTTON_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR);
            }
        });

        return button;
    }

    private void refreshTable() {
        DefaultTableModel model = (DefaultTableModel) paymentTable.getModel();
        model.setRowCount(0);
        
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(
                 "SELECT p.*, s.name as salesman_name FROM payment p " +
                 "LEFT JOIN salesman s ON p.salesman_id = s.salesman_id")) {
            while (rs.next()) {
                String salesmanName = rs.getString("salesman_name");
                String salesmanId = rs.getString("salesman_id");
                String salesmanDisplay = salesmanName != null ? 
                    salesmanName + " (" + salesmanId + ")" : salesmanId;
                
                model.addRow(new Object[]{
                    rs.getString("payment_id"),
                    rs.getString("bill_id"),
                    rs.getString("payment_date"),
                    rs.getDouble("amount"),
                    rs.getString("payment_method"),
                    salesmanDisplay
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载收费数据失败: " + e.getMessage());
        }
    }

    private void updatePayment() {
        try {
            // 从业务员选择框中提取业务员ID
            String selectedSalesman = salesmanCombo.getSelectedItem().toString();
            String salesmanId = selectedSalesman.substring(selectedSalesman.lastIndexOf("(") + 1, selectedSalesman.lastIndexOf(")"));

            String sql = "UPDATE payment SET bill_id=?, payment_date=?, amount=?, payment_method=?, salesman_id=? WHERE payment_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, billIdField.getText());
            pstmt.setString(2, paymentDateField.getText());
            pstmt.setDouble(3, Double.parseDouble(amountField.getText()));
            pstmt.setString(4, paymentMethodCombo.getSelectedItem().toString());
            pstmt.setString(5, salesmanId);
            pstmt.setString(6, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "收费信息更新成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "更新收费信息失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "金额必须是数字！");
        }
    }

    private void deletePayment() {
        try {
            String sql = "DELETE FROM payment WHERE payment_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "收费信息删除成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "删除收费信息失败: " + e.getMessage());
        }
    }

    private void searchPayment() {
        try {
            StringBuilder sql = new StringBuilder(
                "SELECT p.*, s.name as salesman_name FROM payment p " +
                "LEFT JOIN salesman s ON p.salesman_id = s.salesman_id WHERE 1=1");
            
            // 构建查询条件
            if (!idField.getText().trim().isEmpty()) {
                sql.append(" AND p.payment_id LIKE ?");
            }
            if (!billIdField.getText().trim().isEmpty()) {
                sql.append(" AND p.bill_id LIKE ?");
            }
            if (!paymentDateField.getText().trim().isEmpty()) {
                sql.append(" AND p.payment_date LIKE ?");
            }
            if (!amountField.getText().trim().isEmpty()) {
                sql.append(" AND p.amount = ?");
            }
            if (paymentMethodCombo.getSelectedItem() != null) {
                sql.append(" AND p.payment_method = ?");
            }
            if (salesmanCombo.getSelectedItem() != null) {
                sql.append(" AND p.salesman_id = ?");
            }

            PreparedStatement pstmt = connection.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (!idField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + idField.getText().trim() + "%");
            }
            if (!billIdField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + billIdField.getText().trim() + "%");
            }
            if (!paymentDateField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + paymentDateField.getText().trim() + "%");
            }
            if (!amountField.getText().trim().isEmpty()) {
                pstmt.setDouble(paramIndex++, Double.parseDouble(amountField.getText().trim()));
            }
            if (paymentMethodCombo.getSelectedItem() != null) {
                pstmt.setString(paramIndex++, paymentMethodCombo.getSelectedItem().toString());
            }
            if (salesmanCombo.getSelectedItem() != null) {
                String selectedSalesman = salesmanCombo.getSelectedItem().toString();
                String salesmanId = selectedSalesman.substring(selectedSalesman.lastIndexOf("(") + 1, selectedSalesman.lastIndexOf(")"));
                pstmt.setString(paramIndex++, salesmanId);
            }

            // 清空表格
            DefaultTableModel model = (DefaultTableModel) paymentTable.getModel();
            model.setRowCount(0);

            // 执行查询并显示结果
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String salesmanName = rs.getString("salesman_name");
                String salesmanId = rs.getString("salesman_id");
                String salesmanDisplay = salesmanName != null ? 
                    salesmanName + " (" + salesmanId + ")" : salesmanId;
                
                model.addRow(new Object[]{
                    rs.getString("payment_id"),
                    rs.getString("bill_id"),
                    rs.getString("payment_date"),
                    rs.getDouble("amount"),
                    rs.getString("payment_method"),
                    salesmanDisplay
                });
            }

            if (model.getRowCount() == 0) {
                JOptionPane.showMessageDialog(this, "未找到匹配的记录！");
            }

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "查询失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "金额必须是数字！");
        }
    }

    private void clearFields() {
        idField.setText("");
        billIdField.setText("");
        paymentDateField.setText("");
        amountField.setText("");
        paymentMethodCombo.setSelectedIndex(0);
        salesmanCombo.setSelectedItem(null);
    }
} 